/*
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 */

//
//  MainViewController.h
//  HelloWorld
//
//  Created by ___FULLUSERNAME___ on ___DATE___.
//  Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//

#import "MainViewController.h"
#import "CDVWebServer.h"
#import "UIController.h"
#import "OnboardingViewController.h"
#import "HookWebViewController.h"
#import "DeviceUtil.h"
#import "Constants.h"
#import "CDVSplashViewControl.h"
#import "SplashView.h"


@interface MainViewController ()

@property(strong, nonatomic)CDVWebServer *webServer;
@property(strong,nonatomic)SplashView       *splash;



@end

@implementation MainViewController

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
    // UIStatusBarStyleDefault = 0 黑色文字，浅色背景时使用
    // UIStatusBarStyleLightContent = 1 白色文字，深色背景时使用
}

- (BOOL)prefersStatusBarHidden
{
    return NO; // 返回NO表示要显示，返回YES将hiden
}

- (id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Uncomment to override the CDVCommandDelegateImpl used
        // _commandDelegate = [[MainCommandDelegate alloc] initWithViewController:self];
        // Uncomment to override the CDVCommandQueue used
        // _commandQueue = [[MainCommandQueue alloc] initWithViewController:self];
    }
    return self;
}

- (id)init
{
    self = [super init];
    if (self) {
        // Uncomment to override the CDVCommandDelegateImpl used
        // _commandDelegate = [[MainCommandDelegate alloc] initWithViewController:self];
        // Uncomment to override the CDVCommandQueue used
        // _commandQueue = [[MainCommandQueue alloc] initWithViewController:self];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark View lifecycle

- (void)viewWillAppear:(BOOL)animated
{
    // View defaults to full size.  If you want to customize the view's size, or its subviews (e.g. webView),
    // you can do so here.
    
    [super viewWillAppear:animated];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

//    [self setHomeBackground];
    [self setHomeBackgroundWithImageSets];
    
    needReloadStartPage = YES;
    
    //[self.view bringSubviewToFront:self.webView];
    self.webView.frame = CGRectMake(self.webView.frame.origin.x, self.webView.frame.origin.y+20, self.webView.frame.size.width, self.webView.frame.size.height-20);
    [self.webView setOpaque:NO];
    [self.webView setBackgroundColor:[UIColor clearColor]];
    [self.webView setAllowsInlineMediaPlayback:YES];
    [self.webView setHidden:YES];
    
//    //splashView
    SplashView *splash = [[SplashView alloc]initWithFrame:CGRectMake(0, 20, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height)];
    splash.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    [self.view addSubview:splash];
    self.splash =splash;
    [self.splash show];
   
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(webServerStartOk)
                                                 name:KEYSPLASHHIDE
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(splashShow)
                                                 name:KEYSPLASHSHOW
                                               object:nil];
    localResourceHandler = [[LocalResourceHandler alloc] init];
    localResourceHandler.delegate = self;
    [self startConfigUpdate];
    
}

- (void)startConfigUpdate {
    self.webView.hidden = YES;
    [self dismissViewControllerAnimated:NO completion:NULL];
    [localResourceHandler verifyLocalResource];
    currentState = CurrentStateDownLoadConfig;
    [self showLoadingView];
}

- (void)loadStartPage {
    
    if ([StandaloneMode boolValue]) {
        [self showOnboarding];
    } else {
        if (needReloadStartPage) {
            [self showLoadingView];
            self.webView.scrollView.bounces = NO;
            self.webView.dataDetectorTypes = UIDataDetectorTypeNone;
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(webServerSuccess:)
                                                         name:KEYPLUGINWEBSERVERSUCCESS
                                                       object:nil];
            
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(webServerfail:)
                                                         name:KEYPLUGINWEBSERVERFAILE
                                                       object:nil];
            self.webServer = [[CDVWebServer alloc]init];
            
            [self.webServer startWebServer];
            needReloadStartPage = NO;
        } else {
            self.webView.hidden = NO;
        }
        
    }
}

- (void)showOnboarding {
    
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"OnboardingHasShow"]) {
        OnboardingViewController *controller = [[[OnboardingViewController alloc] init] autorelease];
        [self.navigationController pushViewController:controller animated:YES];
    } else {
        HookWebViewController *controller = [[HookWebViewController alloc] init];
        [self.navigationController pushViewController:controller animated:YES];
    }
}


- (void)startUpdateConfigInForeground {
    self.webView.hidden = YES;
    [self startConfigUpdate];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter]removeObserver:KEYPLUGINWEBSERVERSUCCESS];
    [[NSNotificationCenter defaultCenter]removeObserver:KEYPLUGINWEBSERVERFAILE];
    [[NSNotificationCenter defaultCenter]removeObserver:KEYSPLASHHIDE];
    [[NSNotificationCenter defaultCenter]removeObserver:KEYSPLASHSHOW];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    
}

- (void)changeMenuBackFromGreenWithMenuId:(NSString *)menuId {
    NSString *jsCall = [NSString stringWithFormat:@"changeMenuBackFromGreenLaiSee('%@');",menuId];
    
    [self.webView stringByEvaluatingJavaScriptFromString:jsCall];
}

-(void) showLoadingView {
    
    [UIController showLoading:self.view];
    
}

-(void) removeLoadingView {
    
    [UIController hideLoading];
}

- (void)showWebView {
    [self removeLoadingView];
    [self.webView setHidden:NO];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    // Return YES for supported orientations
    return [super shouldAutorotateToInterfaceOrientation:toInterfaceOrientation];
}

/* Comment out the block below to over-ride */

/*
 - (UIWebView*) newCordovaViewWithFrame:(CGRect)bounds
 {
 return[super newCordovaViewWithFrame:bounds];
 }
 */

#pragma mark UIWebDelegate implementation

- (void)webViewDidFinishLoad:(UIWebView*)theWebView
{
    // Black base color for background matches the native apps
    theWebView.backgroundColor = [UIColor whiteColor];
//    if (self.webView.hidden) {
//        [self performSelector:@selector(showWebView) withObject:nil afterDelay:1.5];
//    }
    
    return [super webViewDidFinishLoad:theWebView];
}
#pragma mark UIWebServeRefresh implementation

- (void) webServerSuccess:(NSNotification *)notification
{
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:notification.object]]];
    NSLog(@"加载网页%@", notification.object);
//    BYODPlugIn *plugIn = [[BYODPlugIn alloc] init];
//    [plugIn showGSR:nil];
    
}

- (void) webServerfail:(NSNotification *)notification
{
    ////web server fail
    
}

/* Comment out the block below to over-ride */

/*
 
 
 
 - (void) webView:(UIWebView*)theWebView didFailLoadWithError:(NSError*)error
 {
 return [super webView:theWebView didFailLoadWithError:error];
 }
 
 - (BOOL) webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
 {
 return [super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType];
 }
 */


- (void)showNetworkErrorAlert {
    //comment for HSBC 150
    //To do
    /*
    NSString *title = @"Cannot connect to network";
    NSString *message = @"An error has occurred connecting to the service. Please check your internet connection or try again later.";
    NSString *cancelButtonTitle = @"OK";
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil];
    [alertView show];
    [alertView release];
     */
}
     

- (void)showRetryAlert {
    NSString *title = @"Error";
    NSString *message = @"Sorry, there was a problem downloading the latest update.";
    NSString *cancelButtonTitle = @"Cancel";
    NSString *retryButtonTitle = @"Try Again";
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:retryButtonTitle,nil];
    [alertView show];
    [alertView release];
}

- (void)startFetchWebResource {
    needReloadStartPage = YES;
    currentState = CurrentStateDownloadClientPack;
    [self removeLoadingView];
    [UIController showProgress:0.0 message:@"" inView:self.view];
}

- (void)updateFetchWebResourceProgress:(float)progress {
    [UIController showProgress:progress message:@"" inView:self.view];
}

- (void)fetchResourceDone {
    currentState = CurrentStateDownloadResourceDone;
    [self removeLoadingView];
    [UIController hideProgress];
    [self loadStartPage];
}

- (void)fetchResourceError {
    [self removeLoadingView];
    if (currentState == CurrentStateDownloadClientPack) {
        [UIController hideProgress];
        [self showRetryAlert];
    } else {
        [self showNetworkErrorAlert];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [localResourceHandler downloadNextResource];
    } else {
        //        abort();
    }
}
- (void)setHomeBackgroundWithImageSets{
    self.view.frame = [UIApplication sharedApplication].delegate.window.bounds;
    backgroudImageView.frame = CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height-20);
    [backgroudImageView setImage:[UIImage imageNamed:@"backgroundImage"]];
    [self.view sendSubviewToBack:backgroudImageView];
    
}
- (void)setHomeBackground {
    NSString *imageName = nil;
    
    UIDeviceResolution uiDeviceResolution = [DeviceUtil currentResolution];
    
    if ((uiDeviceResolution == UIDevice_iPhoneStandardRes)||(uiDeviceResolution == UIDevice_iPhoneHiRes))
    {
        imageName = @"4s.png";
    }
    else if (uiDeviceResolution == UIDevice_iPhoneTallerHiRes)
    {
        imageName = @"5s.png";
    }
    // Added by Joe [4 May.2015]. for supporting iPhone6/6+
    else if (uiDeviceResolution == UIDevice_iPhone6Res) {
        
        imageName = @"6.png";
    }
    else if (uiDeviceResolution == UIDevice_iPhone6PlusRes) {
        
        imageName = @"6p.png";
    }
    else
    {
        // no support other device, use the default
        imageName = @"4s.png";
    }
    backgroudImageView.frame = CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height-20);
    [backgroudImageView setImage:[UIImage imageNamed:imageName]];
    [self.view sendSubviewToBack:backgroudImageView];
}

#pragma mark webserver
-(void)splashShow
{
    [self.splash show];
}
-(void)webServerStartOk
{
    [self removeLoadingView];
    [self.splash hide];
    [self showWebView];
}

@end

@implementation MainCommandDelegate

/* To override the methods, uncomment the line in the init function(s)
 in MainViewController.m
 */

#pragma mark CDVCommandDelegate implementation

- (id)getCommandInstance:(NSString*)className
{
    return [super getCommandInstance:className];
}

/*
 NOTE: this will only inspect execute calls coming explicitly from native plugins,
 not the commandQueue (from JavaScript). To see execute calls from JavaScript, see
 MainCommandQueue below
 */
- (BOOL)execute:(CDVInvokedUrlCommand*)command
{
    return [super execute:command];
}

- (NSString*)pathForResource:(NSString*)resourcepath;
{
    return [super pathForResource:resourcepath];
}


@end

@implementation MainCommandQueue

/* To override, uncomment the line in the init function(s)
 in MainViewController.m
 */
- (BOOL)execute:(CDVInvokedUrlCommand*)command
{
    return [super execute:command];
}

@end
